// pages/goods_detail/index.js
import { request } from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{},
    collectList:[],
    isCollected:false,
  },
  GoodsInfo:{},
  goods_id:'',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {goods_id} = options;
    this.goods_id =goods_id;
    this.getGoodsDetail(goods_id)
  },
  async getGoodsDetail(goods_id){
    const goodsObj = await request({url:'/goods/detail',data:{goods_id}})
    this.GoodsInfo = goodsObj
    this.setData({
      goodsObj:{
        goods_name:goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics:goodsObj.pics
      }
    })
  },
  handlePreviewImage(e){
    const urls = this.GoodsInfo.pics.map(v=>v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    })
  },
  handleCartAdd(){
    let cart = wx.getStorageSync('cart') || []; 
    const index = cart.findIndex(item=>{return item.goods_id === this.GoodsInfo.goods_id})
    if(index === -1){
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      
      cart.push(this.GoodsInfo)
    }else{
      cart[index].num++;
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '插入成功',
      icon: 'success',
      mask: true
    });
  },
  handleCollect(e){
    if(this.data.collectList.includes(this.goods_id)){
      this.data.collectList = this.data.collectList.filter(item=>{
        return item != this.goods_id;
      })
      this.data.isCollected = false;
    }else{
      this.data.collectList.push( this.goods_id)      
      this.data.isCollected = true;
    }
    this.setData({
      collectList:this.data.collectList,
      isCollected:this.data.isCollected
    })
    wx.setStorageSync('collectList',this.data.collectList)
    
  }

})